<?php
namespace Mobile\Controller;
use User\Api\UserApi;

class UserController extends MobileController {
    /**
    * 获取验证码
    * 
    */
    public function getVerifyCode($mobile=''){
        if(empty($mobile)) $this->err('手机号码不能为空！');
        
        if(!preg_match("/^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/",$mobile)){    
            $this->err('手机号码格式不正确！');
        }

        $where['mobile'] = $mobile;
        
        $vercode = S("sess_$mobile");
        if(!empty($vercode)){
            if(NOW_TIME - $vercode['verify_time'] < 60) {
                $this->err('60秒内只允许发送一次验证码。');
            }
        }
        
        //每个IP限制每分钟限10条
        $ip = get_client_ip();
        $ip_num = S("sess_$ip");
        if(empty($ip_num)) $ip_num = 0;
        if($ip_num>10){
            $this->err('同一个IP发送的验证码超出限制！');
        }else{
            S("sess_$ip",$ip_num+1,array('expire'=>60));
        }
              
        //查找记录，是否有60秒内发过的
        $model = M('SmsLog');
        $result = $model->where($where)->order('logid desc')->limit(1)->select();
        if($result){
            $posttime = $result[0]['posttime'];
            if((strtotime('now')-strtotime($posttime))<=60){ //60秒之内只允许发送一次
                $this->err('60秒内只允许发送一次验证码。');
            }
        }
        
        $code = rand(1000,9999);
        $content ="尊敬的用户，您的验证码是：" . $code .",有效时间10分钟。";
        $ret = $this->sendSmsMsg($mobile,$content);

        $vercode = array(
            'mobile' => $mobile,
            'verify_code' => $code,
            'verify_time' => NOW_TIME,
        );
        
        S("sess_$mobile",$vercode,array('expire'=>600));
        
        if($ret){
            $retArr = explode("\n",$ret);
            list($resptime,$respstatus) = explode(',',$retArr[0]);
            $msgid = $retArr[1];
            //记录到数据库
            $data['mobile'] = $mobile;
            $data['content'] = $content;
            $data['verifycode'] = $code;
            $data['resptime'] = $resptime;
            $data['respstatus'] = $respstatus;
            $data['msgid'] = $msgid;
            $model->add($data);
            
            $this->succ('ok');
        }else{
            $this->err('短信接口异常！');
        }
    }
    
    /**
    * 用户登录
    * 
    * @param mixed $mobile 手机号码
    * @param mixed $verfycode 短信验证码
    * @param mixed $channel 渠道号
    */
    public function login($mobile,$verfycode,$channel=''){
        /* 调用UC登录接口登录 */
        $user = new UserApi;
        
        if(empty($verfycode)){
            $this->err('验证码不能为空！');
        }else{ //如果用手机号码登录的话
            $uid = $user->login($mobile, $verfycode, 6);
        }
        if(0 < $uid){ //UC登录成功
            /* 登录用户 */
            $Member = D('Member');
            if($Member->login($uid)){ //登录用户
                $data['uid'] = $uid;
                $expire = NOW_TIME + C('USER_TOKEN_EXPIRE');
                $data['expire'] = $expire;
                $data['usertoken'] = $this->encrypt_usertoken($uid,$expire,$channel);
                //TODO: 删除这段测试用代码
                session('usertoken',$data['usertoken']);
                
                session('uid',$uid);
                $this->succ($data);
            } else {
                $this->err($Member->getError());
            }

        } else { //登录失败
            switch($uid) {
                case -1: $error = '用户不存在或被禁用！'; break; //系统级别禁用
                case -2: $error = '密码错误！'; break;
                case -3: $error = '短信验证码已过期！'; break;
                case -4: $error = '短信验证码有误！'; break;
                default: $error = '未知错误！'; break; // 0-接口参数错误（调试阶段使用）
            }
            $this->err($error);
        }        
    }
       
    protected function sendSmsMsg($mobile,$content){
                
        $post_data = array();
        $post_data['account'] = iconv('GB2312', 'GB2312',C('SMS_ACCOUNT'));
        $post_data['pswd'] = iconv('GB2312', 'GB2312',C('SMS_PASSWORD'));
        $post_data['mobile'] =$mobile;
        $post_data['msg']=mb_convert_encoding("$content",'UTF-8', 'auto');
        $post_data['needstatus'] = 'true';
        $url=C('SMS_URL'); 
        $o="";
        foreach ($post_data as $k=>$v)
        {
           $o.= "$k=".urlencode($v)."&";
        }
        $post_data=substr($o,0,-1);
         
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function getToken(){
        $usertoken =  $this->encrypt_usertoken(17,1439885953);
        session('usertoken',$usertoken);
    }    

    /**
    * 获取用户信息
    * 
    */
    public function info(){
        if(empty($this->uid)){
            $this->err('用户未登录！');
        }        
        $where['uid'] = $this->uid;
        $where['status'] = 1;
        $model = M('Member');
        $res = $model->where($where)->find();
        if(empty($res)) $this->err('找不到对应用户的信息或用户已禁用！');
        if(empty($res['cash_passwd'])) 
            $res['cash_passwd_isset'] = false;
        else
            $res['cash_passwd_isset'] = true;
            
        if(empty($res['login_password_changes'])){
            $res['login_passwd_isset'] = false;
        }else{
            $res['login_passwd_isset'] = true;            
        }
        unset($res['login_password_changes']);
        unset($res['cash_passwd']);//去掉支付密码
        unset($res['status']);
        $res['headimg'] = $this->getFullUrl(get_cover($res['headimg'],'path'));
        $this->succ($res);
    }
    
    /**
    * 上传头像
    * 
    */
    public function uploadHeadimg(){
        if(empty($this->uid)){
            $this->err('用户未登录！');
        }        

        /* 调用文件上传组件上传文件 */
        $Picture = D('Picture');
        $pic_driver = C('PICTURE_UPLOAD_DRIVER');
        $info = $Picture->upload(
            $_FILES,
            C('PICTURE_UPLOAD_HEADIMG'),
            C('PICTURE_UPLOAD_DRIVER'),
            C("UPLOAD_{$pic_driver}_CONFIG")
        ); //TODO:上传到远程服务器

        /* 记录图片信息 */
        if($info){
            $headimg = 0;
            foreach($info as $file){
                $headimg = $file['id'];
            }
            $data['headimg'] = $headimg;
            $where['uid'] = $this->uid;
            M('Member')->where($where)->save($data);
            $ret = $this->getFullUrl(get_cover($headimg,'path'));
            $this->succ($ret);
        } else {
            $this->err($Picture->getError());
        }
    }
    
    /**
    * 姓名编辑
    * 
    * @param mixed $name
    */
    public function updateName($name=''){
        if(empty($this->uid)){
            $this->err('用户未登录！');
        }        
        $data['realname'] = $name;
        $where['uid'] = $this->uid;
        M('Member')->where($where)->save($data);
        
        $this->info();
    }
        
    /**
    * 性别修改
    * 
    * @param mixed $sex
    */
    public function updateSex($sex=''){
        if(empty($this->uid)){
            $this->err('用户未登录！');
        }        
        $data['sex'] = $sex;
        $where['uid'] = $this->uid;
        M('Member')->where($where)->save($data);
        
        $this->info();
    }
    
    /**
    * 地址列表
    * 
    */
    public function address(){
        if(empty($this->uid)){
            $this->err('用户未登录！');
        }        
        $where['uid'] = $this->uid;
        $res = M('UserAddress')->where($where)->select();
        $this->succ($res);
    }
    
    /**
    * 保存地址
    * 
    * @param mixed $province
    * @param mixed $city
    * @param mixed $area
    * @param mixed $address
    * @param mixed $mobile
    * @param mixed $recvname
    */
    public function saveAddr($province='',$city='',$area='',$address='',$mobile='',$recvname='',$aid=''){
        if(empty($this->uid)){
            $this->err('用户未登录！');
        }
        $data['uid'] = $this->uid;
        $data['province'] = $province;
        $data['city'] = $city;
        $data['area'] = $area;
        $data['address'] = $address;
        $data['mobile'] = $mobile;
        $data['recvname'] = $recvname;
        
        $model = M('UserAddress');
        if(empty($aid)){
            $aid = $model->add($data);
        }else{
            $where['uid'] = $this->uid;
            $where['aid'] = $aid;
            $model->where($where)->save($data);
        }
        $where['uid'] = $this->uid;
        $where['aid'] = $aid;
        $res = $model->where($where)->find();
        $this->succ($res);
    }
    
    /**
    * 删除地址
    * 
    * @param mixed $aid
    */
    public function delAddr($aid=''){
        if(empty($this->uid)){
            $this->err('用户未登录！');
        }
        if(empty($aid)){
            $this->err('未指定要删除的地址');
        }
        $model = M('UserAddress');
        $where['uid'] = $this->uid;
        $where['aid'] = $aid;
        $model->where($where)->delete();
        $this->succ('删除成功！');
    }

    /**
    * 修改登陆密码
    * 
    */
    public function chgPass(){
        if(empty($this->uid)){
            $this->err('用户未登录！');
        }
        //获取参数
        $password   =   I('oldpass');
        $repassword = I('repass');
        $data['password'] = I('newpass');
        empty($password) && $this->err('请输入原密码');
        empty($data['password']) && $this->err('请输入新密码');
        empty($repassword) && $this->err('请输入确认密码');

        if($data['password'] !== $repassword){
            $this->err('您输入的新密码与确认密码不一致');
        }

        $Api = new UserApi();
        $res = $Api->updateInfo($this->uid, $password, $data);
        if($res['status']){
            $this->succ('修改密码成功！');
        }else{
            $err = $res['info'];
            if(is_numeric($err)){
                $this->err($this->showRegError($err));
            }else{
                $this->err($err);
            }
        }
    }
    
    public function chgCashPass(){
        if(empty($this->uid)){
            $this->err('用户未登录！');
        }
        
        //获取参数
        $password   =   I('oldpass');
        $repassword = I('repass');
        $newpass = I('newpass');
        //empty($password) && $this->err('请输入原密码');
        empty($newpass) && $this->err('请输入新密码');
        empty($repassword) && $this->err('请输入确认密码');

        if($newpass !== $repassword){
            $this->err('您输入的新密码与确认密码不一致');
        }

        $model = M('Member');
        $where['uid'] = $this->uid;
        $cashpass = $model->where($where)->getFieldById($this->uid,'cash_passwd');
        if(empty($cashpass)){
            //$this->err('未设置过交易密码，请通过忘记密码进行设置！');
            $hash_pass = think_md5($newpass, C('DATA_AUTH_KEY'));
            $data['cash_passwd'] = $hash_pass;
            $model->where($where)->save($data);
            $this->succ('修改成功！');
        }else{
            empty($password) && $this->err('请输入原密码');
            $hash_pass = think_md5($password, C('DATA_AUTH_KEY'));
            if($hash_pass != $cashpass){
                $this->err('原有支付密码不正确！');
            }else{
                $hash_pass = think_md5($newpass, C('DATA_AUTH_KEY'));
                $data['cash_passwd'] = $hash_pass;
                $model->where($where)->save($data);
                $this->succ('修改成功！');
            }
        }
        $this->err($cashpass);
        
    }
    
    /**
    * 修改手机号码第一步
    * 
    */
    public function chgMobile1(){
        if(empty($this->uid)){
            $this->err('用户未登录！');
        }
        $mobile = I('mobile');
        $verfyCode = I('verfyCode');
        if(empty($verfyCode)){
            $this->err('请输入验证码!');
        }
        if(!validateMobile($mobile)){
            $this->err('手机号码无效！');
        }
        $model = M('Member');
        $where['uid'] = $this->uid;
        $user_mobile = $model->where($where)->getField('mobile');
        if($user_mobile != $mobile){
            $this->err('原有手机号码不正确！');
        }
        if($this->check_sms_verfiy($mobile,$verfyCode)){
            S('sess_' . $this->uid .'_step_chgMobile1',true);
            $this->succ('校验成功！');
        }else{
            $this->err('验证码错误！');
        }
    }
    
    /**
    * 修改手机号码第二步
    * 
    */
    public function chgMobile2(){
        if(empty($this->uid)){
            $this->err('用户未登录！');
        }
        $mobile = I('mobile');
        $verfyCode = I('verfyCode');
        if(empty($verfyCode)){
            $this->err('请输入验证码!');
        }
        if(!validateMobile($mobile)){
            $this->err('手机号码无效！');
        }
        $step = S('sess_' . $this->uid .'_step_chgMobile1');
        if($step){
            $model = M('UcenterMember');
            $where['uid'] = array('neq',$this->uid);
            $where['mobile'] = $mobile;
            $user = $model->where($where)->find();
            if($user){
                $this->err('新手机号码已被占用！');
            }
            if($this->check_sms_verfiy($mobile,$verfyCode)){
                S('sess_' . $this->uid .'_step_chgMobile1',null);
                
                //这里更新两个地方
                unset($where);
                $where['id'] = $this->uid;
                unset($data);
                $data['mobile'] = $mobile;
                $model->where($where)->save($data);
                unset($where);
                $where['uid'] = $this->uid;
                M('Member')->where($where)->save($data);
                $this->succ('修改成功！');
            }else{
                $this->err('验证码错误！');
            }
        }else{
            $this->err('请先验证已有手机!');
        }
    }
    
    
    protected function check_sms_verfiy($mobile,$verfycode){
        $vercode = S("sess_$mobile");
        if(empty($vercode)) {
            return false; //短信验证码过期
        }
        // session 过期
        if(NOW_TIME - $vercode['verify_time'] > C('SMS_EXPIRE_TIME')) {
            S("sess_$mobile", null);
            return false; //短信验证码过期
        }
        if($verfycode == $vercode['verify_code']){
            S("sess_$mobile", null); //重置清空
            return true; //登录成功，返回用户ID
        }
        return false;
    }

    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0){
        switch ($code) {
            case -1:  $error = '用户名长度必须在16个字符以内！'; break;
            case -2:  $error = '用户名被禁止注册！'; break;
            case -3:  $error = '用户名被占用！'; break;
            case -4:  $error = '密码长度必须在4-30个字符之间！'; break;
            case -5:  $error = '邮箱格式不正确！'; break;
            case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
            case -7:  $error = '邮箱被禁止注册！'; break;
            case -8:  $error = '邮箱被占用！'; break;
            case -9:  $error = '手机格式不正确！'; break;
            case -10: $error = '手机被禁止注册！'; break;
            case -11: $error = '手机号被占用！'; break;
            default:  $error = '未知错误';
        }
        return $error;
    }

    
}